package com.sparrow.manage.util;

import java.io.*;
import java.util.Base64;
import java.util.Random;
import java.util.UUID;

public class FileStore {

    public static final String STORE_FOLDER = "FrogFiles";

    private String path;  // 存储路径

    private Random random = new Random();

    public FileStore(String path) {
        if(path == null){
            throw new IllegalArgumentException("文件存储路径不能为空.");
        }
        if(!path.endsWith("/")){
            path += "/";
        }
        this.path = path + STORE_FOLDER + "/";
        File directory = new File(this.path);
        if(!directory.exists()){
            directory.mkdir();
        }
    }

    public String getSuffix(String fileName){
        if(fileName == null) return "";
        int suffixIndex = fileName.lastIndexOf(".");

        String suffix = "";
        if(suffixIndex > 0){
            suffix = fileName.substring(suffixIndex);
        }
        return suffix;
    }

    public String generateRandomFileName(String realFileName){
        String suffix = this.getSuffix(realFileName);
        return UUID.randomUUID().toString().replace("-", "") + suffix;
    }

    private File generateFile(String pos, String randomName){
        String location = path + pos;
        File directory = new File(location);
        if(!directory.exists()){
            directory.mkdir();
        }

        return new File(location + "/" + randomName);
    }

    /**
     * 保存文件至指定位置
     * @return 返回存储路径: 随机文件夹(0-49) + "/" + uuid + 文件后缀
     */
    public String saveFile(InputStream inputStream, String fileName) throws IOException {
        String randomName = generateRandomFileName(fileName);
        String pos = assignStoreLocation();
        generateFile(pos, randomName);

        try(OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(generateFile(pos, randomName)))){
            byte[] buf = new byte[1024];
            int len;
            while((len = inputStream.read(buf)) != -1){
                outputStream.write(buf, 0, len);
            }
        }

        return pos + "/" + randomName;
    }

    public String assignStoreLocation(){
        return String.valueOf(random.nextInt(50)); // 生成50内的随机存储位置
    }

    public String saveBase64(String base64, String fileName) throws IOException {
        String randomName = generateRandomFileName(fileName);
        String pos = assignStoreLocation();
        generateFile(pos, randomName);

        try(OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(generateFile(pos, randomName)))){
            String[] baseStrs = base64.split(",");
            int index = baseStrs.length > 1 ? 1 : 0;

            byte[] buf;
            buf = Base64.getDecoder().decode(baseStrs[index].trim());	// base64正文

            for(int i = 0; i < buf.length; i++) {
                if (buf[i] < 0) {
                    buf[i] += 256;
                }
            }

            outputStream.write(buf);
        }


        return pos + "/" + randomName;
    }

    /**
     * 删除文件
     * @param storePath
     * @return
     */
    public boolean deleteFile(String storePath){
        File file = new File(storePath);
        if(file.exists() && file.isFile()){
            file.delete();
            return true;
        }
        return false;
    }

}
